package com.company.cloud.art.modules.mgr.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.api.request.ArtistAddReq;
import com.company.cloud.art.modules.api.request.ArtistQueryReq;
import com.company.cloud.art.modules.api.request.ArtistUpdateReq;
import com.company.cloud.art.modules.api.response.Artist;
import com.company.cloud.art.modules.api.response.ArtistQueryResp;
import com.company.cloud.art.modules.base.entity.ArtistInfo;
import com.company.cloud.art.modules.base.entity.CustUserInfoVto;
import com.company.cloud.art.modules.base.service.ArtistInfoService;
import com.company.cloud.art.modules.cache.service.ArtistCacheService;
import com.company.cloud.art.modules.cache.utils.ArtConvertUtils;
import com.company.cloud.art.modules.cache.utils.ArtNoUtils;
import com.company.cloud.art.modules.mgr.mapper.ExpoJoinMapper;
import com.company.cloud.art.modules.mgr.service.ActArtistMgrService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.company.modules.api.response.CompanySimple;
import com.company.cloud.company.modules.api.service.CompanyRemoteService;
import com.company.cloud.product.modules.api.response.ProductSimple;
import com.company.cloud.product.modules.api.service.ProductRemoteService;
import com.company.cloud.tag.modules.api.response.Label;
import com.company.cloud.tag.modules.api.service.LabelRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;

@Service
public class ActArtistMgrServiceImpl implements ActArtistMgrService {

    @Autowired
    private ArtistInfoService artistInfoService;

    @Autowired
    private ArtistCacheService artistCacheService;

    @Autowired
    private LabelRemoteService labelRemoteService;

    @Autowired
    private ProductRemoteService productRemoteService;

    @Autowired
    private ExpoJoinMapper mapper;

    @Autowired
    private CompanyRemoteService companyRemoteService;

    @Override
    public ArtistQueryResp artistQuery(ArtistQueryReq request) {
        IPage<ArtistInfo> page = artistInfoService.page(new Page<>(request.getPage(), request.getRows()),
                new QueryWrapper<ArtistInfo>()
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .eq(CheckUtils.hasText(request.getArtistNo()), "artist_no", request.getArtistNo())
                        .like(CheckUtils.hasText(request.getName()), "name", request.getName())
                        .eq(StringUtils.hasText(request.getType()), "type", request.getType())
                        .eq(CheckUtils.hasText(request.getSex()), "sex", request.getSex())
                        .eq(CheckUtils.hasText(request.getNationCode()), "nation_code", request.getNationCode())
                        .like(CheckUtils.hasText(request.getTitle()), "title", request.getTitle())
                        .likeLeft(CheckUtils.hasText(request.getTags()), "tags", request.getTags())
                        .eq(CheckUtils.hasText(request.getCompanyNo()),"company_no",request.getCompanyNo())
                        .orderByDesc("orders")
                       // .apply("OrderBy cdt desc")

        );

        Set<String> tagIds=new HashSet<String>();
        Set<String> prdIds=new HashSet<>();
        page.getRecords().forEach(item->{
            Set<String> _tags= StrSplitUtils.parse2set(item.getTags(),String.class);
            Set<String> _prdIds=StrSplitUtils.parse2set(item.getRepresentativeWork(),String.class);
            tagIds.addAll(_tags);
            prdIds.addAll(_prdIds);
        });


//        System.out.println("+++++++ tagIds="+ JSON.toJSONString(tagIds));
//        System.out.println("+++++++ prdIds="+ JSON.toJSONString(prdIds));
        BaseClientResult<Map<String, ProductSimple>> prdRespResult = productRemoteService.getProductSimpleMapByIds(prdIds);
        BaseClientResult<Map<String, Label>> labelRespResult = labelRemoteService.getLabelMapByIds(tagIds);
        Map<String, ProductSimple>  prdResp=BaseClientResult.getResultData(prdRespResult);
        Map<String, Label> labelResp=BaseClientResult.getResultData(labelRespResult);
//        System.out.println("+++++++++++++++ end");
//        System.out.println(JSON.toJSONString(prdResp));
//        System.out.println("+++++++++++++++ 11111111111111");
//        System.out.println(JSON.toJSONString(labelResp));
//        System.out.println("+++++++++++++++ end");

        IPage<Artist> data=page.convert(new Function<ArtistInfo, Artist>() {
            @Override
            public Artist apply(ArtistInfo entity) {
                CompanySimple companySimple = null;
                if (StrUtil.isNotEmpty(entity.getCompanyNo())) {
                    System.out.println("+++++++++++= CompanySimple start");
                    BaseClientResult<CompanySimple> companySimpleRest = companyRemoteService.getCompanySimple(entity.getCompanyNo());
                    companySimple = BaseClientResult.getResultData(companySimpleRest);
                    if (companySimple != null) {
                        System.out.println("++++++++++ " + companySimple.getName());
                    }
                    System.out.println("+++++++++++= CompanySimple end ");
                }
                if (StrUtil.isNotEmpty(entity.getCompanyNo())) {
                    final CustUserInfoVto custUserInfoVto = mapper.CustUserId(entity.getUserId());
                    if(custUserInfoVto!=null){
                        return ArtConvertUtils.getArtistVto(entity,labelResp,prdResp,companySimple,custUserInfoVto);
                    }
                }
                return ArtConvertUtils.getArtistVto(entity,labelResp,prdResp,companySimple);
            }

        });
        ArtistQueryResp resp = new ArtistQueryResp();
        resp.setRecords(data.getRecords());
        resp.setTotal(data.getTotal());
        resp.setPages(data.getPages());
        resp.setSize(data.getSize());
        resp.setCurrent(data.getCurrent());
        return resp;
    }

    @Override
    public Artist artistInfo(String artistNo) {
        return artistCacheService.getArtistByDB(artistNo);
    }

    @Override
    public List<Artist> artistInfoList(Set<String> artistNos) {
        List<Artist> data=new ArrayList<>();
         if(CollectionUtils.isEmpty(artistNos)){
             return data;
         }

        List<ArtistInfo> list = artistInfoService.list(new QueryWrapper<ArtistInfo>()
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                .in("artist_no",artistNos)
        );

         if(CollectionUtils.isEmpty(list)){
             return data;
         }
         list.forEach(item->{
            data.add(ArtConvertUtils.getArtist(item));
         });
        return data;
    }

    @Override
    public Map<String, Artist> artistInfoMap(Set<String> artistNos) {
        Map<String, Artist> data= new HashMap<>();
        if(CollectionUtils.isEmpty(artistNos)){
            return data;
        }
        List<ArtistInfo> list = artistInfoService.list(new QueryWrapper<ArtistInfo>()
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                .in("artist_no",artistNos)
        );
        if(CollectionUtils.isEmpty(list)){
            return data;
        }
        list.forEach(item->{
            data.put(item.getArtistNo(),ArtConvertUtils.getArtist(item));
        });
        return data;
    }

    @Override
    public void artistAdd(ArtistAddReq request, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(request);
        ArtistInfo entity=new ArtistInfo();
        BeanUtil.copyProperties(request,entity,"representativeWork","tags");
        entity.setArtistNo(ArtNoUtils.getArtistNo());
        entity.setRepresentativeWork(StrSplitUtils.list2string(request.getRepresentativeWork()));
        entity.setTags(StrSplitUtils.list2string_prefix(request.getTags()));
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        artistInfoService.save(entity);
    }


    @Override
    public void artistUpdate(ArtistUpdateReq request, LoginSimpleUserInfo userInfo) {
        ValidatorUtils.validate(request);
        ArtistInfo entity=artistInfoService.getById(request.getArtistNo());
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if(StrUtil.isNotEmpty(request.getCompanyNo())){
            entity.setCompanyNo(request.getCompanyNo());
        }
        entity.setName(request.getName());
        entity.setType(request.getType());
        entity.setHeadImg(request.getHeadImg());
        entity.setBackgroundImg(request.getBackgroundImg());
        entity.setSex(request.getSex());
        entity.setNationCode(request.getNationCode());
        entity.setTitle(request.getTitle());
//        entity.setRepresentativeWork(StrSplitUtils.list2string(request.getRepresentativeWork()));
        entity.setMemo(request.getMemo());
        entity.setDetail(request.getDetail());
        entity.setBirthday(request.getBirthday());
        entity.setImgs(request.getImgs());
        entity.setTags(StrSplitUtils.list2string_prefix(request.getTags()));
        entity.setOrders(request.getOrders());
        entity.setMetaKeywords(request.getMetaKeywords());
        entity.setMetaDescription(request.getMetaDescription());
        entity.setBackgroundColour(request.getBackgroundColour());
        entity.setBizValue1(request.getBizValue1());
        entity.setBizValue2(request.getBizValue2());
        entity.setBizValue3(request.getBizValue3());
        entity.setBizValue4(request.getBizValue4());
        entity.setBizValue5(request.getBizValue5());

        entity.setBizValue6(request.getBizValue6());
        entity.setBizValue7(request.getBizValue7());
        entity.setBizValue8(request.getBizValue8());
        entity.setBizValue9(request.getBizValue9());
        entity.setBizValue10(request.getBizValue10());

        entity.addEditParam(userInfo);
        artistInfoService.updateById(entity);

        artistCacheService.removeArtistByCache(request.getArtistNo());
        //todo:更新ES
    }

    @Transactional
    @Override
    public void artistDel(String artistNo, LoginSimpleUserInfo userInfo) {
        ArtistInfo entity=artistInfoService.getById(artistNo);
        if(entity==null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        artistInfoService.removeById(artistNo);
        artistCacheService.removeArtistByCache(artistNo);
        //todo:更新ES
    }

    @Override
    public void artistDelPrd(Set<String> artistNos, String prdNo) {
        List<ArtistInfo> artistList= artistInfoService.listByIds(artistNos);
        this._artistDelPrd(artistList,prdNo);
    }

    private void _artistDelPrd( List<ArtistInfo> artistList, String prdNo){
        if(CollectionUtils.isEmpty(artistList)){
            return ;
        }
        List<ArtistInfo> updateEntity=new ArrayList<>();
        artistList.forEach(entity->{
            if(entity!=null && BaseConstant.EnabledEnum.ENABLED.getCode().equals(entity.getRowsState())) {
                Set<String> prdNos= StrSplitUtils.parse2set(entity.getRepresentativeWork(),String.class);
                prdNos.remove(prdNo);
                entity.setRepresentativeWork(StrSplitUtils.list2string(prdNos));
                updateEntity.add(entity);
            }
        });
        if(updateEntity.size()>0){
            artistInfoService.updateBatchById(updateEntity);
        }
    }

    @Override
    public void artistAddPrd(Set<String> artistNos, String prdNo) {
        List<ArtistInfo> artistList= artistInfoService.listByIds(artistNos);
        if(CollectionUtils.isEmpty(artistList)){
            return ;
        }
        List<ArtistInfo> updateEntity=new ArrayList<>();
        artistList.forEach(entity->{
            if(entity!=null && BaseConstant.EnabledEnum.ENABLED.getCode().equals(entity.getRowsState())) {
                Set<String> prdNos= StrSplitUtils.parse2set(entity.getRepresentativeWork(),String.class);
                prdNos.add(prdNo);
                entity.setRepresentativeWork(StrSplitUtils.list2string(prdNos));
                updateEntity.add(entity);
            }
        });
        if(updateEntity.size()>0){
            artistInfoService.updateBatchById(updateEntity);
        }
    }

    @Override
    public void artistEditPrd(Set<String> artistNos, String prdNo) {
        List<ArtistInfo> artistList= artistInfoService.list(new QueryWrapper<ArtistInfo>().like("representative_work",prdNo));
        this._artistDelPrd(artistList,prdNo);
        this.artistAddPrd(artistNos,prdNo);
    }


}
